package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.KillConstants;
import cn.itsource.ymcc.constant.PayConstants;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.dto.PreOrderDto;
import cn.itsource.ymcc.openfeign.OrderOpenfeign;
import cn.itsource.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Component
@RocketMQMessageListener(
        consumerGroup = "KillConsumer",
        topic = KillConstants.TOPIC_ORDER_TIMEOUT,
        selectorExpression = KillConstants.TAGS_ORDER_TIMEOUT
)
@Slf4j
public class KillConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private OrderOpenfeign orderOpenfeign;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String orderNo = new String(body, Constants.UTF8);
            //我先从  order服务里面去查询  有没有生成订单
            JsonResult order = orderOpenfeign.getOrder(orderNo);
            if(!order.getSuccess()){
                //如果没有
                PreOrderDto o = (PreOrderDto)redisTemplate.opsForValue().get(KillConstants.KEY_PREFIX_PRE_ORDER + orderNo);
                redisTemplate.delete(KillConstants.KEY_PREFIX_PRE_ORDER+o.getUserId());
                //回滚库存
                redisTemplate.opsForValue().increment(KillConstants.KILL_STORE + o.getCourseId(),o.getCount());
            }
            // 如果有 直接删除 redis的伪订单数据
            redisTemplate.delete(KillConstants.KEY_PREFIX_PRE_ORDER+orderNo);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
